package reduce.fz.com.reduce.util;

import android.content.Context;
import android.content.res.Configuration;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import reduce.fz.com.reduce.util.base.ReduceApplication;

/**
 * Created by qingshengzheng on 15/12/29.
 */

public class MovieRecorder implements SurfaceHolder.Callback {
    private MediaRecorder mediarecorder;
    boolean isRecording;
    private MediaPlayer mPlayer;
    private Context context;
    private TimeListener listener;
    private Camera camera;
    private SurfaceHolder surfaceHolder;
    private SurfaceView surfaceView;





    public MovieRecorder(Context context) {
        this.context = context;
    }

    public MovieRecorder(Context context,SurfaceView surfaceView)
    {
        this.context=context;
        this.surfaceView=surfaceView;
        this.surfaceHolder=surfaceView.getHolder();
        surfaceHolder.addCallback(this);
    }



    public MovieRecorder(Context context, TimeListener listener,SurfaceView surfaceView) {
        this(context);
        this.listener = listener;
        this.surfaceView=surfaceView;
        this.surfaceHolder=surfaceView.getHolder();
        surfaceHolder.addCallback(this);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        openCamera();

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }

    public static interface TimeListener {
        public void time(int seconds);
    }

    public int getDefalutCameraId() {
        int gTotalCameraCount = Camera.getNumberOfCameras();
        int gDefaultCameraId = 0;
// Find the ID of the default camera
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        for (int i = 0; i < gTotalCameraCount; i++) {
            Camera.getCameraInfo(i, cameraInfo);
            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
                gDefaultCameraId = i;
                break;
            }
        }
        return gDefaultCameraId;
    }


    public void openCamera() {
        camera = Camera.open();
        try {
            //设置预览监听
            camera.setPreviewDisplay(surfaceHolder);
            Camera.Parameters parameters = camera.getParameters();

            if (ReduceApplication.getInstance().getResources().getConfiguration().orientation
                    != Configuration.ORIENTATION_LANDSCAPE) {
                parameters.set("orientation", "portrait");
                camera.setDisplayOrientation(90);
                parameters.setRotation(90);
            } else {
                parameters.set("orientation", "landscape");
                camera.setDisplayOrientation(0);
                parameters.setRotation(0);
            }
            camera.setParameters(parameters);
            //启动摄像头预览
            camera.startPreview();
            System.out.println("camera.startpreview");

        } catch (IOException e) {
            e.printStackTrace();
            camera.release();
            System.out.println("camera.release");
        }
    }


    public void startRecording(final SurfaceView surfaceView) {
        mediarecorder = new MediaRecorder();// 创建mediarecorder对象
       // Camera mCamera = Camera.open(getDefalutCameraId());
        Camera.Parameters params = camera.getParameters();
        camera.setDisplayOrientation(90);// 旋转了90度
        camera.setParameters(params);
        camera.unlock();// 解锁
        mediarecorder.setCamera(camera);
        mediarecorder.setOrientationHint(90);
// 设置录制视频源为Camera(相机)
        mediarecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
// 设置录制完成后视频的封装格式THREE_GPP为3gp.MPEG_4为mp4
        mediarecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
// 设置录制的视频编码h263 h264
        mediarecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
// 设置视频录制的分辨率。必须放在设置编码和格式的后面，否则报错
        mediarecorder.setVideoSize(176, 144);
// 设置录制的视频帧率。必须放在设置编码和格式的后面，否则报错
        mediarecorder.setVideoFrameRate(20);
        mediarecorder.setPreviewDisplay(surfaceView.getHolder().getSurface());
// 设置视频文件输出的路径
        lastFileName = newFileName();
        mediarecorder.setOutputFile(lastFileName);
        try {
// 准备录制
            mediarecorder.prepare();
// 开始录制
            mediarecorder.start();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        isRecording = true;
        timeSize = 0;
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                timeSize++;
                if (listener != null) listener.time(timeSize);
                if (timeSize >= 60)
                    startRecording(surfaceView);
            }
        }, 0, 1000);
    }

    Timer timer;
    int timeSize = 0;
    private String lastFileName;

    public String stopRecording() {
        String newPath = "";
        if (mediarecorder != null) {
// 停止
            mediarecorder.stop();
            mediarecorder.release();
            mediarecorder = null;
            timer.cancel();
            if (null != lastFileName && !"".equals(lastFileName)) {
                File f = new File(lastFileName);
                String name = f.getName().substring(0,
                        f.getName().lastIndexOf(".3gp"));
                name += "_" + timeSize + "s.3gp";
                newPath = f.getParentFile().getAbsolutePath() + "/"
                        + name;
                if (f.renameTo(new File(newPath))) {
                    int i = 0;
                    i++;
                }
                return newPath;
            }
        }
        return newPath;
    }

    public String newFileName() {
        try {
            return File.createTempFile("/mov_", ".3gp").getAbsolutePath();
        } catch (IOException e) {
// TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }

    public void release() {
        if (mediarecorder != null) {
// 停止
            mediarecorder.stop();
            mediarecorder.release();
            mediarecorder = null;
        }
    }


    public void play(String fileName, SurfaceView view) {
        mPlayer = new MediaPlayer();
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mPlayer.setDisplay(view.getHolder()); // 定义一个SurfaceView播放它
        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer arg0) {
                stop();
            }
        });
        try {
            mPlayer.setDataSource(fileName);
            mPlayer.prepare();
        } catch (IllegalStateException e) {
// TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
// TODO Auto-generated catch block
            e.printStackTrace();
        }
        mPlayer.start();
    }

    public void stop() {
        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
    }
}
